<?php

namespace paper\helper;

class Storage
{
    private string $directory;
    private array $data = [];

    public static function directory(string $directory): Storage
    {
        return new static($directory);
    }

    public function __construct(string $directory)
    {
        $this->directory = PAPER_APP_PATH . DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . $directory . '.json';
        if (is_file($this->directory)) {
            $this->data = json_decode(file_get_contents($this->directory), true);
        }
    }

    public function put($key, $value)
    {
        $this->data[$key] = $value;
    }

    public function setAll($data)
    {
        $this->data  = $data;
    }

    public function all(): array
    {
        return $this->data;
    }

    public function get($key, $default)
    {
        return $this->data[$key] ?? $default;
    }

    public function save()
    {
        file_put_contents($this->directory, json_encode($this->data));
    }
}